package helplib

import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"os"
	pathp "path"
	"runtime"
	"strconv"
	"strings"
)

//PathExists 判断文件夹是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

//FileExists 判断文件是否存在
func ReplaceFileExt(path, newExt string) string {
	return strings.TrimSuffix(path, pathp.Ext(path)) + newExt
}

//FileExists 判断文件是否存在
func FileExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

//FileCopy 文件Copy
func FileCopy(srcFileName, dstFileName string) (bool, error) {
	srcFile, err := os.Open(srcFileName)
	if err != nil {
		return false, errors.New("open srcfile err = " + err.Error())
	}
	defer srcFile.Close()
	//打开dstFileName
	dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		return false, errors.New("open dstfile err = " + err.Error())
	}
	defer dstFile.Close()
	if _, err = io.Copy(dstFile, srcFile); err != nil {
		return false, errors.New("复制错误：" + err.Error())
	}
	return true, nil
}

//FileDelete FileDelete
func FileDelete(fileName string) (bool, error) {
	err := os.Remove(fileName)
	return err == nil, err
}

//PathCreat 创建文件夹
func PathCreat(path string) (bool, error) {
	// 创建文件夹
	err := os.Mkdir(path, os.ModePerm)
	if err != nil {
		return false, err
	}
	return true, nil
}

//GetGID 获取协程编号（仅用于调试）
func GetGID() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

//GetFilesAndDirs 获取指定目录下的所有文件和目录
func GetFilesAndDirs(dirPth string, extFilter string) (files []string, dirs []string, err error) {
	return getFilesAndDirs("", dirPth, extFilter)
}

//getFilesAndDirs 获取指定目录下的所有文件和目录
func getFilesAndDirs(deepPath string, dirPth string, extFilter string) (files []string, dirs []string, err error) {
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, nil, err
	}

	PthSep := string(os.PathSeparator)
	//suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
	if deepPath != "" {
		deepPath = deepPath + PthSep
	}
	for _, fi := range dir {
		if fi.IsDir() { // 目录, 递归遍历
			dirs = append(dirs, dirPth+PthSep+fi.Name())
			getFilesAndDirs(deepPath+fi.Name(), dirPth+PthSep+fi.Name(), extFilter)
		} else {
			// 过滤指定格式
			lens := len(extFilter)
			if lens > 0 {
				ok := strings.HasSuffix(fi.Name(), "."+extFilter)
				if ok {
					files = append(files, deepPath+fi.Name())
				}
			} else {
				files = append(files, deepPath+fi.Name())
			}
		}
	}

	return files, dirs, nil
}
